package in.muton.edushare.documentModel.excel;

import java.util.ArrayList;
import java.util.List;

public class StringUtils {
	
	public static void main(String[] args){
		String a = "My name is Nishant Neeraj kaksha \nsaat udai pratap inter college wowow";
		System.out.println(breakIntoLines(a, 20).toString());
	}
	
	public static String breakIntoLines(String input, int maxCharPerLine){
		String lines = "";
		List<String> l = breakIntoListOfLines(input, maxCharPerLine);
		for(int i=0; i<l.size(); i++){
			if(i>0)
				lines = lines+"\n";
			lines = lines + l.get(i);
		}
		return lines;
	}
	
	/**
	 * 
	 * @param input
	 * @param maxCharPerLine
	 * @return List of strings, each elements represent one line of maxCharPerLine or less
	 */
	public static List<String> breakIntoListOfLines(String input, int maxCharPerLine){
		List<String> lines = new ArrayList<String>();
		if(!isValid(input))
			return lines;
		
		//Split by user entered line breaks
		input = input.trim().replace("\r\n", "\n").replace("\r", "\n");
		String[] origlines = input.split("\n");
		
		//take each chunk and break them by maxCharPerLine
		for(String line: origlines){
			while(line.length()>maxCharPerLine){
				int lastSpace = line.substring(0, maxCharPerLine).lastIndexOf(' ');
				if(lastSpace < 0)
					lastSpace = maxCharPerLine; //if no space found, break the line
				
				if(lastSpace>0){
					lines.add(line.substring(0, lastSpace));
					line = line.substring(lastSpace).trim();
				}
			}
			lines.add(line);
		}
		return lines;
	}
	
	/**
	 * is the given input not-null, non-empty string?
	 * @param str
	 * @return
	 */
	public static boolean isValid(String str){
		boolean isValid = false;
		if(str!=null && !str.replace(" ", "").equals(""))
			isValid = true;
		return isValid;
	}

}
